package com.house.java.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckCodeServlet extends HttpServlet {


	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//第一步：
		//生成一张图片
		//创建内存映像对象
		BufferedImage image = 
			new BufferedImage(60, 30, BufferedImage.TYPE_INT_RGB);
		//获得画笔对象
		Graphics g= image.getGraphics();
		//设置画笔的颜色
		Random r = new Random(System.currentTimeMillis());
//		g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
		g.setColor(new Color(255,255,255));
		//设置背景
		g.fillRect(0, 0, 60, 30);
		//生成一个随机字符串
		//String number = r.nextInt(9999)+"";
		char[] c = {'a','b','c','d','e','f','g',
					'h','j','k','l','m','n',
					'p','q','r','s','t',
					'u','v','w','x','y','z',
					'2','3','4','5','6','7','8','9'};
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 4; i++) {
			sb.append(c[r.nextInt(c.length)]);
		}
		String number = sb.toString();
		//将字符串绑定到session中
		HttpSession session = request.getSession();
		session.setAttribute("checkCode", number);
		//给画笔再换一个颜色
		g.setColor(new Color(0,0,0));
		//设置字体
		g.setFont(new Font("宋体",Font.BOLD,24));
		//将字符串画在图片上
		g.drawString(number, 5, 15);//这个坐标是字符窜的左上角离图片左上角的距离
		//加干扰线 x<30 y<80
		for(int i=0;i<5;i++){
			g.drawLine(r.nextInt(80), r.nextInt(30),r.nextInt(80), r.nextInt(30));
		}
		//第二步：
		//将图片压缩并输出到客户端，原始图片太大，压缩，节省网络资源
		response.setContentType("image/jpeg");
		OutputStream ops = response.getOutputStream();
		javax.imageio.ImageIO.write(image, "jpeg", ops);//三个参数:内存图片映像 图片的格式  字节输出流
		
		
	}

}
